package com.cxhc.framework.aspectj;

import com.cxhc.common.annotation.Integral;
import com.cxhc.common.enums.IntegralType;
import com.cxhc.common.utils.SecurityUtils;
import com.cxhc.system.domain.app.IntegralRecords;
import com.cxhc.system.service.app.IIntegralRecordsService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * 积分切面
 *
 * @author wuxuan
 */
@Aspect
@Order(1)
@Component
public class IntegralRecordsAspect {

    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private IIntegralRecordsService integralRecordsService;

    @Pointcut("@annotation(com.cxhc.common.annotation.Integral)"
            + "|| @within(com.cxhc.common.annotation.Integral)")
    public void dsPointCut()
    {

    }

    @Before("dsPointCut()")
    public void before(JoinPoint point)
    {

        try {
            Integral integral = getIntegral(point);
            IntegralType value = integral.value();
            String desc = value.getDesc();
            Long integralValue = value.getIntegral();
            IntegralRecords integralRecords = new IntegralRecords();
            integralRecords.setUserId(SecurityUtils.getUserId());
            integralRecords.setCompanyName(SecurityUtils.getUserEntName());
            integralRecords.setUserName(SecurityUtils.getUseRealName());
            //操作积分
            integralRecords.setIntegral(integralValue);
            Long balance = SecurityUtils.getUserIntegral();
            integralRecords.setBalance(balance);
            integralRecords.setStatus(1);
            integralRecords.setContent(desc);
            integralRecordsService.insertIntegralRecords(integralRecords);
            logger.info("积分新增成功");
        }catch (Exception e){
            logger.info("积分新增失败");

        }

    }

    /**
     * 获取注解信息
     */
    public Integral getIntegral(JoinPoint point)
    {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Integral integral = AnnotationUtils.findAnnotation(signature.getMethod(), Integral.class);
        if (Objects.nonNull(integral))
        {
            return integral;
        }

        return AnnotationUtils.findAnnotation(signature.getDeclaringType(), Integral.class);
    }
}
